package frankenstein.algo;
import java.util.*;
import frankenstein.interfaces.IFitnessListener;
import frankenstein.datastructures.*;

public class FitnessPublisher implements
		frankenstein.interfaces.FitnessPublisher {

	//The collection of fitnessListeners
	ArrayList<IFitnessListener> listenerList;
	
	//The collection of evolutions, evolution at index i corresponds to fitnesslistener at index i
	ArrayList<Evolution> evolutionsList;
	
	public FitnessPublisher(){
		evolutionsList = new ArrayList<Evolution>();
		listenerList = new ArrayList<IFitnessListener>();
	}
	
	public void register(IFitnessListener listener) {
		listenerList.add(listener);

	}

	private void publish(){
	
		ListIterator<IFitnessListener> li = listenerList.listIterator();
		while(li.hasNext()){
			IFitnessListener ifl = li.next();
			Evolution e = evolutionsList.get(li.previousIndex());
			Generation g = e.getLatestPeriod().getLastGeneration();
			int generationId = g.getId();
			long fitness = 0;
			if(Frankenstein.eliteFitness){
	
				fitness = g.getGenerationEliteFitness();
			}
			else if(Frankenstein.bestFitness){
	
				fitness = g.getGenerationBestFitness();
			}
	
			
	
			ifl.update(e, generationId, fitness);
			
		}
	}
	
	
	public ArrayList<IFitnessListener> getListenerList() {
		return listenerList;
	}
	public void setListenerList(ArrayList<IFitnessListener> listenerList) {
		this.listenerList = listenerList;
	}
	
	public ArrayList<Evolution> getEvolutionsList() {
		return evolutionsList;
	}
	public void setEvolutionsList(ArrayList<Evolution> evolutionsList) {
		this.evolutionsList = evolutionsList;
	}
	public void addEvolution(Evolution e){
		this.evolutionsList.add(e);
	}
	public void fitnessChange(){

		publish();
	}
}
